<template>
  <div class="user-profile">
    <h1>个人中心</h1>
    <div v-if="user">
      <img :src="`http://192.168.239.53:8082/${user.userPic}`" alt="用户头像" class="user-img" />
      <p><strong>用户名：</strong>{{ user.username }}</p>
      <p><strong>昵称：</strong>{{ user.nickname }}</p>
      <p><strong>性别：</strong>{{ getGenderText(user.gender) }}</p>
      <p><strong>性别：</strong>{{ getIdentityText(user.gender) }}</p>
      
      <!-- 修改按钮 -->
      <el-button type="primary" @click="openEditDialog">修改个人信息</el-button>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>

    <!-- 修改用户信息的对话框 -->
    <el-dialog :title="'修改个人信息'" v-model="openDialog" width="500px">
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="头像" prop="userPic">
          <el-upload
            action="http://192.168.239.53:8082/api/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            list-type="picture-card"
            :limit="1"
            :auto-upload="true"
            :before-upload="beforeUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <p v-if="editForm.userPic">已上传头像：{{ editForm.userPic }}</p>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import { fetchUser, updateUser } from '@/api/user';  // 假设你有 `fetchUser` 和 `updateUser` API

export default {
  name: 'UserProfile',
  data() {
    return {
      user: null, // 用户信息
      openDialog: false, // 控制对话框的显示与隐藏
      editForm: {
        username: '',
        nickname: '',
        password: '',
        userPic: '', // 用户头像
      }, // 用于编辑的表单数据
      editRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      }, // 表单验证规则
    };
  },
  methods: {
    getGenderText(gender) {
      gender = String(gender);
      return gender === '0' ? '男' : gender === '1' ? '女' : '保密';
    },
     getIdentityText(identity) {
      identity = String(identity);
      return identity === '1' ? '普通用户' : identity === '0' ? '管理员' : '保密';
    },
    // 打开编辑对话框，填充当前用户数据
    openEditDialog() {
      this.editForm = { ...this.user }; // 将当前用户信息填充到编辑表单
      this.openDialog = true; // 打开对话框
    },

    // 取消编辑，关闭对话框
    cancelDialog() {
      this.openDialog = false;
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 调用 API 更新用户信息
          updateUser(this.editForm)
            .then(() => {
              console.log("this.editForm",this.editForm);
              this.user = { ...this.editForm }; // 更新页面上的用户信息
              this.$message.success('个人信息更新成功');
              this.openDialog = false; // 关闭对话框
            })
            .catch((error) => {
              console.error('更新用户信息失败:', error);
              this.$message.error('更新个人信息失败');
            });
        } else {
          this.$message.error('请填写完整信息');
        }
      });
    },

    // 上传成功后处理
    handleUploadSuccess(response) {
      if (response && response.data) {
        this.editForm.userPic = response.data; // 获取文件路径并存入 form 数据
      } else {
        this.$message.error('图片上传失败');
      }
    },

    // 上传失败时的处理
    handleUploadError() {
      this.$message.error('图片上传失败');
    },

    // 上传前的处理，检查 token 或其他条件
    beforeUpload(file) {
      const token = sessionStorage.getItem('token');
      if (token) {
        file.headers = { Authorization: `Bearer ${token}` };
        return true;
      } else {
        this.$message.error('未登录，请先登录');
        return false;
      }
    },
  },
  async created() {
    try {
      const userInfo = await fetchUser(); // 获取用户信息
      this.user = userInfo; // 将返回的数据赋值给 user
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
  },
};
</script>

<style scoped>
.user-profile {
  padding: 20px;
}
.user-profile h1 {
  margin-bottom: 20px;
}
.user-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}
p {
  margin: 5px 0;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
